package com.meritdata.cloud.data.service.application.controller;

import com.meritdata.cloud.data.base.Page;
import com.meritdata.cloud.data.service.application.model.Application;
import com.meritdata.cloud.data.service.application.service.IApplicationService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RequestMapping("/application")
@Controller
public class ApplicationController {
	
	@Autowired
	private IApplicationService service;

	@RequestMapping("/page")
	@ResponseBody
	public Page<Application> page(){
		Page page = new Page();
		page.setPageNum(1);
		page.setPageSize(4);
		return service.page(page);
	}

	@RequestMapping("/list")
	@ResponseBody
	public List<Application> list(){
		return service.all();
	}


	@RequestMapping("/save")
	@ResponseBody
	public boolean save(Application application, @RequestParam(value="file",required = true) MultipartFile file){
		try {
			application.setCredential(file.getBytes());
			application.setCredentialName(file.getOriginalFilename());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return service.save(application);
	}

	@RequestMapping("/update")
	@ResponseBody
	public boolean update(Application application, @RequestParam(value="file",required = true) MultipartFile file){
		try {
			application.setCredential(file.getBytes());
			application.setCredentialName(file.getOriginalFilename());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return service.udpate(application);
	}

	@RequestMapping("/delete")
	@ResponseBody
	public boolean delete(@RequestParam Long id){
		return service.delete(id);
	}

	@RequestMapping("/get/{id}")
	@ResponseBody
	public Application get(@PathVariable Long id){
		return service.load(id);
	}

	@RequestMapping("/credential/{id}")
	public void getCredential(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response){
		Application application = service.get(id);
		if(application != null && application.getCredential() != null && application.getCredential().length > 0){
			try {
				IOUtils.copy(new ByteArrayInputStream(application.getCredential()), response.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
